package com.lineng.service.impl;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.lineng.dao.ActivityMapper;
import com.lineng.pojo.Activity;
import com.lineng.service.ActivityService;
import com.lineng.util.UrlUtil;
import com.lineng.util.VerificationUtil;

@Service
public class ActivityServiceImpl implements ActivityService {

	@Autowired
	ActivityMapper activityMapper;

	@Autowired
	private HttpServletRequest request;

	public List<Activity> getActivity() {

		List<Activity> activities = activityMapper.selectByExample(null);
		try {
			if (VerificationUtil.verification(request) == 0) {
				for (int i = 0; i < activities.size(); i++) {
					if (activities.get(i).getReader() != null && activities.get(i).getReader() != 0) {
						int result = activities.get(i).getReader() + 1;
						activityMapper.updateActivityReader(result);
					} else {
						activityMapper.updateActivityReader(1);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return activities;
	}

	public List<Activity> getActivityByDate(Date startDate, Date endDate) {

		if (VerificationUtil.verification(request) == 1) {
			return activityMapper.getActivitiesByDate(startDate, endDate);
		}
		return null;
	}

	public int insertActivity(Activity activity, String username) {
		// 验证用户的权限
		if (VerificationUtil.verification(request) == 1) {
			activity.setDate(new Date());
			activity.setPeople(username);
			// 判断路径开始是否带有http，如果没有就把https拼接上
			if (activity.getUrl().startsWith("http")) {
				return activityMapper.insertSelective(activity);
			} else {
				activity.setUrl(UrlUtil.url(activity.getUrl()));
				return activityMapper.insertSelective(activity);
			}
		}
		return 0;
	}

	public int updateActivity(Activity activity, String username) {
		if (VerificationUtil.verification(request) == 1) {
			activity.setDate(new Date());
			activity.setPeople(username);
			if (activity.getUrl().startsWith("http")) {
				return activityMapper.updateByPrimaryKeySelective(activity);
			} else {
				activity.setUrl(UrlUtil.url(activity.getUrl()));
				return activityMapper.updateByPrimaryKeySelective(activity);
			}
		}
		return 0;
	}

	public int deleteActivity(Integer[] id) {
		int num = 0;
		if (VerificationUtil.verification(request) == 1) {
			if (id.length > 0) {
				num = activityMapper.deleteById(id);
				if (id.length == num) {
					return num;
				}
			}
		}
		return 0;
	}
}
